package com.kensure.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import co.kensure.frame.ResultRowInfo;
import co.kensure.frame.ResultRowsInfo;
import co.kensure.http.RequestUtils;
import co.kensure.io.FileUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kensure.shike.baobei.model.SKBaobei;
import com.kensure.shike.baobei.service.SKBaobeiService;
import com.kensure.shike.qiniu.service.QiNiuService;

/**
 * 图片
 * 
 * @author fankaidi
 *
 */
@Controller
@RequestMapping(value = "file")
public class FileController {

	@Resource
	private QiNiuService qiNiuService;
	@Resource
	private SKBaobeiService sKBaobeiService;

	/**
	 * 上传图片,给富文本框,返回结果不一样
	 */
	@ResponseBody
	@RequestMapping(value = "addfiles.do", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	public JSONObject addfiles(MultipartHttpServletRequest request) {
		Collection<List<MultipartFile>> multipartFiles = request.getMultiFileMap().values();
		JSONObject map = new JSONObject();
		map.put("errno", 0);
		JSONArray data = new JSONArray();
		map.put("data", data);
		for (List<MultipartFile> filelist : multipartFiles) {
			for (MultipartFile file : filelist) {
				InputStream is = null;
				try {
					String name = file.getOriginalFilename();
					is = file.getInputStream();
					String im = qiNiuService.upload(is,name);
					data.add(im);
				} catch (IOException e) {
					throw new RuntimeException(e);
				} finally {
					FileUtils.close(is);
				}
			}
		}
		return map;
	}

	/**
	 * 上传图片,自己用的
	 */
	@ResponseBody
	@RequestMapping(value = "upfiles.do", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	public ResultRowsInfo upfiles(MultipartHttpServletRequest request) {
		Collection<List<MultipartFile>> multipartFiles = request.getMultiFileMap().values();
		List<String> data = new ArrayList<>();
		for (List<MultipartFile> filelist : multipartFiles) {
			for (MultipartFile file : filelist) {
				InputStream is = null;
				try {
					String name = file.getOriginalFilename();
					is = file.getInputStream();
					String im = qiNiuService.upload(is,name);
					data.add(im);
				} catch (IOException e) {
					throw new RuntimeException(e);
				} finally {
					FileUtils.close(is);
				}
			}
		}
		return new ResultRowsInfo(data);
	}

	/**
	 * 下载图片
	 */
	@ResponseBody
	@RequestMapping(value = "download.do", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	public ResultRowInfo download(HttpServletRequest req, HttpServletResponse rep) {
		JSONObject json = RequestUtils.paramToJson(req);
		Long bbid = json.getLong("id");
		SKBaobei baobei = sKBaobeiService.selectOne(bbid);
		String picurl = baobei.getPicurl();
		
		HttpURLConnection conn = null;
		BufferedOutputStream output = null;
		try {

			URL url = new URL(picurl);
			conn = (HttpURLConnection) url.openConnection();
			// 设置超时间为3秒
			conn.setConnectTimeout(3 * 1000);
			// 防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			// 得到输入流
			InputStream inputStream = conn.getInputStream();

			// 获取自己数组
			byte[] bs = readInputStream(inputStream);
			rep.setContentType("application/octet-stream;charset=ISO8859-1");
			
			output = new BufferedOutputStream(rep.getOutputStream());
			// 中文文件名必须转码为 ISO8859-1,否则为乱码
			String fileNameDown = new String("123.jpg".getBytes(), "ISO8859-1");
			// 作为附件下载
			rep.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);
			output.write(bs);
			rep.flushBuffer();
			
		} catch (Exception e) {

		} // 用户可能取消了下载
		finally {
			if(conn != null){
				conn.disconnect();
			}
			if(output != null){
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return new ResultRowInfo(1);
	}

	
	/**
	 * 下载图片
	 */
	@ResponseBody
	@RequestMapping(value = "downloadurl.do", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	public ResultRowInfo downloadurl(HttpServletRequest req, HttpServletResponse rep) {
		JSONObject json = RequestUtils.paramToJson(req);
		String picurl = json.getString("picurl");
		HttpURLConnection conn = null;
		BufferedOutputStream output = null;
		try {

			URL url = new URL(picurl);
			conn = (HttpURLConnection) url.openConnection();
			// 设置超时间为3秒
			conn.setConnectTimeout(3 * 1000);
			// 防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			// 得到输入流
			InputStream inputStream = conn.getInputStream();

			// 获取自己数组
			byte[] bs = readInputStream(inputStream);
			rep.setContentType("application/octet-stream;charset=ISO8859-1");
			
			output = new BufferedOutputStream(rep.getOutputStream());
			// 中文文件名必须转码为 ISO8859-1,否则为乱码
			String fileNameDown = new String("123.jpg".getBytes(), "ISO8859-1");
			// 作为附件下载
			rep.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);
			output.write(bs);
			rep.flushBuffer();
			
		} catch (Exception e) {

		} // 用户可能取消了下载
		finally {
			if(conn != null){
				conn.disconnect();
			}
			if(output != null){
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return new ResultRowInfo(1);
	}
	
	/**
	 *   * 从输入流中获取字节数组   * @param inputStream   * @return   * @throws
	 * IOException   
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}
}
